package com.photoeditor.demo.ui.widget.collage;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Xfermode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.photoeditor.demo.util.ImageRectUtils;

/**
 * 各种形状的展示图片的View
 * 默认是ImageView 的centerCrop
 */
public class ShapeImageView extends ImageView {

    private Bitmap mSrcBitmap;
    private Matrix mSupportMatrix;

    private Drawable mShapeBitmap;
    private RectF mShapeDrawRect;

    private boolean mInit;

    private RectF mViewRectF;

    private static final Xfermode sXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
    private Paint mDSTPaint;

    private Paint mPaint;

    private Path mClipPath = new Path();
    private int mClipRaduis;
    private boolean mIsClipCircle = false;

    public ShapeImageView(Context context) {
        this(context, null);
    }

    public ShapeImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ShapeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            doInit(ImageRectUtils.getViewRect(this));
        }
        mClipRaduis = getWidth() / 2;
    }

    private void init() {
        setWillNotDraw(false);
        mInit = false;
        mSupportMatrix = new Matrix();
        mViewRectF = new RectF();
        mShapeDrawRect = new RectF();
        mDSTPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mDSTPaint.setXfermode(sXfermode);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    private void doInit(RectF viewRectF) {
        if (!mInit || !mViewRectF.equals(viewRectF)) {
            mInit = true;
            mViewRectF.set(viewRectF);
            mShapeDrawRect.set(0, 0, mViewRectF.width(), mViewRectF.height());
            if (mSrcBitmap != null) {
                resetSupportMatrix();
            }
            invalidate();
        }
    }

    public void setClipCircle(boolean clipCircle) {
        mIsClipCircle = clipCircle;
    }

    public void updateClipCircleRadius(int radius) {
        mClipRaduis = radius;
    }

    @Override
    public void draw(Canvas canvas) {
        // FIXME：这样会导致没有背景
//        super.draw(canvas);
        if (mInit) {
            if (mSrcBitmap != null) {
                if (mShapeBitmap == null) {
                    if (mIsClipCircle) {
                        mClipPath.addCircle(getWidth() / 2, getHeight() / 2, mClipRaduis, Path.Direction.CW);
                        canvas.clipPath(mClipPath);
                    }
                    canvas.drawBitmap(mSrcBitmap, mSupportMatrix, mPaint);
                } else {
                    int count = canvas.saveLayer(0, 0, mViewRectF.width(), mViewRectF.height(), null, Canvas.ALL_SAVE_FLAG);
                    mShapeBitmap.setBounds((int) mShapeDrawRect.left, (int) mShapeDrawRect.top, (int) mShapeDrawRect.right, (int) mShapeDrawRect.bottom);
                    mShapeBitmap.draw(canvas);
//                    canvas.drawBitmap(mShapeBitmap, null, mShapeDrawRect, mPaint);
                    canvas.drawBitmap(mSrcBitmap, mSupportMatrix, mDSTPaint);
                    canvas.restoreToCount(count);
                }
            } else {
                super.draw(canvas);
            }
        }
    }

    /**
     * 初始化SupportMatrix
     */
    private void resetSupportMatrix() {
        mSupportMatrix.reset();
        float bw = mSrcBitmap.getWidth();
        float bh = mSrcBitmap.getHeight();

        float viewW = mViewRectF.width();
        float viewH = mViewRectF.height();

        float w, h;
        float scale;
        float translateX, translateY;
        if (bw / bh >= viewW / viewH) {//比较宽  这时候应高顶着高  才不会显示底图
            h = viewH;
            w = bw * viewH / bh;
            scale = w / bw;
            translateX = (viewW - w) / 2;
            translateY = 0.0f;
        } else {
            w = viewW;
            h = bh * viewW / bw;
            scale = w / bw;
            translateX = 0.0f;
            translateY = (viewH - h) / 2;
        }
        mSupportMatrix.postScale(scale, scale, 0, 0);
        mSupportMatrix.postTranslate(translateX, translateY);
    }

    public void setImageBitmap(Bitmap bitmap) {
        mSrcBitmap = bitmap;
        if (mInit) {
            if (mSrcBitmap != null) {
                resetSupportMatrix();
            }
        }
        invalidate();
    }

    public void setImageResource(int resId) {
        Drawable drawable = getResources().getDrawable(resId);
        if (drawable != null) {
            if (drawable instanceof BitmapDrawable) {
                mSrcBitmap = ((BitmapDrawable) drawable).getBitmap();
                if (mInit) {
                    if (mSrcBitmap != null) {
                        resetSupportMatrix();
                    }
                }
            } else {
                mSrcBitmap = null;
                super.setImageDrawable(drawable);
            }
        } else {
            mSrcBitmap = null;
        }
        invalidate();
    }

    @Override
    public void setImageDrawable(@Nullable Drawable drawable) {
        if (drawable != null) {
            if (drawable instanceof BitmapDrawable) {
                mSrcBitmap = ((BitmapDrawable) drawable).getBitmap();
                if (mInit) {
                    if (mSrcBitmap != null) {
                        resetSupportMatrix();
                    }
                }
            } else {
                mSrcBitmap = null;
                super.setImageDrawable(drawable);
            }
        } else {
            mSrcBitmap = null;
        }
        invalidate();
    }

    public void setShapeBitmap(Bitmap bitmap) {
        mShapeBitmap = new BitmapDrawable(getResources(), bitmap);
        invalidate();
    }

    /**
     * 只有Bitmap时才处理
     *
     * @param resId
     */
    public void setShapeResouce(int resId) {
        if (resId > 0) {
            Drawable drawable = getResources().getDrawable(resId);
            mShapeBitmap = drawable;
        } else {
            mShapeBitmap = null;
        }
        invalidate();
    }

    public void setShapeDrawable(Drawable drawable) {
        if (drawable != null) {
            mShapeBitmap = drawable;
        } else {
            mShapeBitmap = null;
        }
        invalidate();
    }
}
